<template>
  <div class="page">
    <h2>家庭与系统干预（含学校联络）</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按姓名/家庭成员/学校搜索" clearable style="flex:1" @clear="onClear" />

      <el-select v-model="filterType" placeholder="全部类型" style="width:180px">
        <el-option label="全部类型" :value="''" />
        <el-option label="家庭治疗" value="family" />
        <el-option label="学校联络" value="school" />
        <el-option label="社工介入" value="social" />
      </el-select>

      <el-select v-model="filterStatus" placeholder="全部状态" style="width:140px">
        <el-option label="全部" :value="''" />
        <el-option label="进行中" value="ongoing" />
        <el-option label="已完成" value="completed" />
      </el-select>

      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openModal()">新增记录</el-button>
        <el-button @click="exportCSV">导出CSV</el-button>
      </div>
    </div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="姓名" width="140" />
      <el-table-column prop="type" label="干预类型" width="140" />
      <el-table-column prop="familyMembers" label="家庭成员" />
      <el-table-column prop="school" label="学校" width="160" />
      <el-table-column prop="worker" label="负责人/社工" width="140" />
      <el-table-column prop="date" label="记录日期" width="140" />
      <el-table-column prop="status" label="状态" width="110">
        <template #default="{ row }">
          <el-tag :type="row.status==='completed'?'success':'info'">{{ statusMap[row.status] }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="240">
        <template #default="{ row }">
          <el-button size="small" @click="openModal(row.id)">查看/编辑</el-button>
          <el-button size="small" type="primary" @click="contactSchool(row.id)" style="margin-left:8px">联系学校</el-button>
          <el-button size="small" type="danger" @click="deleteOne(row.id)" style="margin-left:8px">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button @click="batchSetStatus('ongoing')">批量标记进行中</el-button>
      <el-button @click="batchSetStatus('completed')">批量标记完成</el-button>
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项</div>
    </div>

    <el-dialog :title="editingId ? '编辑家庭/系统干预' : '新增家庭/系统干预'" v-model="showModal" width="720px">
      <el-form :model="form" label-width="130px">
        <el-form-item label="姓名">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="干预类型">
          <el-select v-model="form.type" style="width:220px">
            <el-option label="家庭治疗" value="family" />
            <el-option label="学校联络" value="school" />
            <el-option label="社工介入" value="social" />
          </el-select>
        </el-form-item>
        <el-form-item label="家庭成员">
          <el-input v-model="form.familyMembers" placeholder="例如：父亲/母亲/兄妹" />
        </el-form-item>
        <el-form-item label="学校/班级">
          <el-input v-model="form.school" />
        </el-form-item>
        <el-form-item label="负责人/社工">
          <el-input v-model="form.worker" />
        </el-form-item>
        <el-form-item label="记录日期">
          <el-date-picker v-model="form.date" type="date" style="width:200px" />
        </el-form-item>
        <el-form-item label="干预内容/结果">
          <el-input v-model="form.content" type="textarea" rows="4" />
        </el-form-item>
        <el-form-item label="后续建议">
          <el-input v-model="form.plan" type="textarea" rows="3" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" style="width:160px">
            <el-option label="进行中" value="ongoing" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const q = ref('');
const filterType = ref('');
const filterStatus = ref('');
const data = ref([]);
const selectedRows = ref([]);
const selectedIds = ref([]);
const showModal = ref(false);
const editingId = ref(null);
const form = reactive({ name:'', type:'family', familyMembers:'', school:'', worker:'', date:'', content:'', plan:'', status:'ongoing' });

const statusMap = { ongoing:'进行中', completed:'已完成' };

onMounted(()=> load());
function load(){
  data.value = [
    {id:1,name:'小明',type:'family',familyMembers:'父亲;母亲',school:'示例中学',worker:'社工王',date:'2025-10-12',content:'家庭疗法，改善沟通',plan:'每周一次家庭治疗',status:'ongoing'},
    {id:2,name:'小红',type:'school',familyMembers:'父亲',school:'示例高中',worker:'李老师',date:'2025-09-30',content:'与学校沟通学业压力',plan:'学校支持计划',status:'completed'}
  ];
}

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !(String(d.name).toLowerCase().includes(qq) || String(d.familyMembers).toLowerCase().includes(qq) || String(d.school).toLowerCase().includes(qq))) return false;
    if(filterType.value && d.type !== filterType.value) return false;
    if(filterStatus.value && d.status !== filterStatus.value) return false;
    return true;
  });
});

watch(selectedRows, v=> selectedIds.value = v.map(i=>i.id));
function onSelectionChange(rows){ selectedRows.value = rows; }
function openModal(id){ editingId.value = id || null; if(id){ const it = data.value.find(x=>x.id===id); if(it) Object.assign(form, JSON.parse(JSON.stringify(it))); } else { Object.assign(form,{ name:'', type:'family', familyMembers:'', school:'', worker:'', date:'', content:'', plan:'', status:'ongoing' }); } showModal.value = true; }
function closeModal(){ showModal.value = false; editingId.value = null; }
function save(){ if(!form.name){ ElMessage.warning('姓名为必填项'); return; } if(editingId.value){ const it = data.value.find(x=>x.id===editingId.value); if(it) Object.assign(it, JSON.parse(JSON.stringify(form))); } else { const nid = (data.value.reduce((s,i)=>Math.max(s,i.id),0) || 0) + 1; data.value.push(Object.assign({id:nid}, JSON.parse(JSON.stringify(form)))); } ElMessage.success('保存成功'); showModal.value = false; }

function contactSchool(id){ const it = data.value.find(x=>x.id===id); if(!it) return; ElMessage.info(`已生成联系记录：${it.school}`); }

function deleteOne(id){ ElMessageBox.confirm('确认删除该记录？','删除确认',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(x=>x.id!==id); ElMessage.success('已删除'); })
  .catch(()=>{});
}

function getSelectedIds(){ return selectedIds.value.slice(); }
function batchSetStatus(s){ const ids = getSelectedIds(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } data.value.forEach(d=>{ if(ids.includes(d.id)) d.status = s; }); ElMessage.success('操作完成'); }
function batchDelete(){ const ids = getSelectedIds(); if(ids.length===0){ ElMessage.warning('请选择至少一项'); return; } ElMessageBox.confirm(`确认删除 ${ids.length} 条记录？`,'批量删除',{ confirmButtonText:'确定', cancelButtonText:'取消', type:'warning' })
  .then(()=>{ data.value = data.value.filter(d=>!ids.includes(d.id)); selectedIds.value=[]; selectedRows.value=[]; ElMessage.success('已删除'); })
  .catch(()=>{});
}

function exportCSV(){ const csv = [ ['id','name','type','familyMembers','school','worker','date','content','plan','status'], ...data.value.map(d=>[d.id,d.name,d.type,d.familyMembers,d.school,d.worker,d.date,d.content||'',d.plan||'',d.status||'']) ]; const csvContent = csv.map(r=>r.map(cell=>`"${String(cell).replace(/"/g,'""')}"`).join(',')).join('\n'); const blob = new Blob([csvContent],{type:'text/csv;charset=utf-8;'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href=url; a.download='family_system_interventions.csv'; document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url); }

function onClear(){ }
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>